<template>
  <a-input v-bind="$attrs" :class="prefixCls" :size="size" :value="state">
    <template #addonAfter>
      <img :src="authCodeURL" @click="refreshAuthCode" />
    </template>
    <template #[item]="data" v-for="item in Object.keys($slots).filter((k) => k !== 'addonAfter')">
      <slot :name="item" v-bind="data"></slot>
    </template>
  </a-input>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useRuleFormItem } from '/@/hooks/component/useFormItem';
  import { useGlobSetting } from '/@/hooks/setting';

  const props = {
    value: { type: String },
    size: { type: String, validator: (v) => ['default', 'large', 'small'].includes(v) },
  };

  export default defineComponent({
    name: 'VerifyCodeInput',
    inheritAttrs: false,
    props,
    setup(props) {
      const { prefixCls } = useDesign('verify-code-input');
      const [state] = useRuleFormItem(props);
      const globSetting = useGlobSetting();
      const verifyCodeUrl = `${globSetting.serveUrl}/authCode.png?${new Date().getTime()}`;
      const authCodeURL = ref(verifyCodeUrl);

      const refreshAuthCode = () => {
        const url = authCodeURL.value.includes('?')
          ? authCodeURL.value.split('?')[0]
          : authCodeURL.value;
        authCodeURL.value = `${url}?${new Date().getTime()}`;
      };
      return { prefixCls, state, authCodeURL, refreshAuthCode };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-verify-code-input';

  .@{prefix-cls} {
    .ant-input-group-addon {
      padding-right: 0;
      width: 100px;
      cursor: pointer;
    }
  }
</style>
